package com.itcast.demo.distributed_lock.controller;

import com.itcast.demo.distributed_lock.service.StockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/lock")
public class DistributedLockTest {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private StockService stockService;

    @PostMapping("/test")
    public void test() {
        // 防止其他线程误删
        String uuid = UUID.randomUUID().toString();
        String lockKey = "lock:coupon:"+"666";
        lock(666,uuid,lockKey);
    }
    private void lock(int couponId, String uuid, String lockKey) {
        // Lua脚本
        String script = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";

        Boolean nativeLock = redisTemplate.opsForValue().setIfAbsent(lockKey,uuid, Duration.ofSeconds(30));
        System.out.println(uuid+"加锁状态："+nativeLock);
        if(Boolean.TRUE.equals(nativeLock)) {
            // 加锁成功
            try {
                // 做相应业务逻辑
                stockService.duck();
            }catch (Exception e) {

            }finally {
                // 解锁
                Long result = (Long) redisTemplate.execute(new DefaultRedisScript<>(script,Long.class),
                        Collections.singletonList(lockKey),uuid);
                System.out.println(uuid+":解锁状态："+result);
            }
        }else {
            // 自旋操作
            try{
                System.out.println("加锁失败，随眠5秒，进行自旋");
                TimeUnit.MILLISECONDS.sleep(5000);
            }catch (Exception e) {
            }
            lock(couponId,uuid,lockKey);
        }
    }
}

